﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Codinfinity.BeIDApplet
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:EidAppletControl runat=server></{0}:EidAppletControl>")]
    public class EidAppletControl : WebControl
    {
        public EidAppletControl()
        {
            AuthMethod = Method.Applet;
            HideDetailsButton = true;
            Language = "fr";
            MessageCssClass = "";
            ButtonClass = "";
            TargetPage = "";
            CursorHeight = 15;
            CursorWidth = 100;
            FontFamily = "arial";
        }
        public enum Method { Applet, EContract }
        public Method AuthMethod{get;set;}
        public bool HideDetailsButton{get;set;}
        public string Language{get;set;}
        public string MessageCssClass{get;set;}
        public string MessageStyle { get; set; }
        public string TitleCssClass { get; set; }
        public string TitleStyle { get; set; }
        public string ButtonClass{get;set;}
        public string TargetPage{get;set;}
        public System.Drawing.Color CursorColor { get; set; }
        public System.Drawing.Color CursorBackColor { get; set; }
        public System.Drawing.Color CursorBorderColor { get; set; }
        public Unit CursorHeight { get; set; }
        public Unit CursorWidth { get; set; }
        public string FontFamily { get; set; }
        
        

        protected override void OnLoad(EventArgs e)
        {
            if (AuthMethod == Method.Applet)
                MyMethod();
            else
                EContractMethod();
            if (HttpContext.Current.Request.QueryString["result"] == "1")
            {
                if ((Identity.Identified) && (Identified != null))
                    Identified(this, new EventArgs());
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            this.Style["position"] = "absolute";
            this.Style["left"] = "50%";
            this.Style["top"] = "50%";
            this.Style["margin-left"] = "-" + (int)(this.Width.Value / 2) + "px";
            this.Style["margin-top"] = "-" + (int)(this.Height.Value / 2) + "px";
            this.Style["box-shadow"]="3px 3px 2px #888";
            this.Style["-moz-box-shadow"]="3px 3px 2px #888";
            this.Style["-webkit-box-shadow"]="3px 3px 2px #888";

        }

        private string JsCode
        {
            get
            {
                if (BackColor == null) BackColor = System.Drawing.Color.White;
                if (CursorColor == null) CursorColor = System.Drawing.Color.Green;
                if (Width == null) Width = new Unit("500");
                if (Height == null) Height = new Unit("300");

                string sid = "";
                string page = "";
                try {
                    sid = SessionManager.ClientSession.SessionID.ToString();
                    page = HttpContext.Current.Request.FilePath;
                }
                catch { }
                string bgcolor = "000000"+BackColor.ToArgb().ToString("X");
                bgcolor = "#"+bgcolor.Substring(bgcolor.Length - 6);
                string ccolor = "000000" + CursorColor.ToArgb().ToString("X");
                ccolor = "#" + ccolor.Substring(ccolor.Length-6);
                string cbcolor = "000000" + CursorBackColor.ToArgb().ToString("X");
                cbcolor = "#" + cbcolor.Substring(cbcolor.Length - 6);
                string cbdcolor = "000000" + CursorBorderColor.ToArgb().ToString("X");
                cbdcolor = "#" + cbdcolor.Substring(cbdcolor.Length - 6);

                string ccolor2 ="000000"+ System.Drawing.Color.FromArgb((int)(CursorColor.R*0.70),(int)(CursorColor.G*0.70), (int)(CursorColor.B*0.70)).ToArgb().ToString("X");
                ccolor2 = "#" + ccolor2.Substring(ccolor2.Length - 6);

                string cbgradient = "background: -webkit-gradient(linear, left top, left bottom, from(" + ccolor + "), to(" + ccolor2 + "));" +
                                    "background: -moz-linear-gradient(top,  " + ccolor + ",  " + ccolor2 + ");" +
                                    "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='"+ccolor+"', endColorstr='"+ccolor2+"');";


                if (page.IndexOf("/") > -1) page = page.Substring(page.LastIndexOf("/") + 1);
                if (page.IndexOf("?") > -1) page = page.Substring(0, page.IndexOf("?"));
                return          "<script type=\"text/javascript\" src=\"https://www.java.com/js/deployJava.js\"></script>\n" +
                                "<script type=\"text/javascript\">\n" +
                                "      var attributes = { \n" +
                                "              code: 'be.fedict.eid.applet.Applet.class',\n" +
                                "              archive: '/eid-applet-package.jar',\n" +
                                "              width: 0,\n" +
                                "              height: 0,\n" +
                                "              mayscript: 'true'\n" +
                                "          };\n" +
                                "      var parameters = {\n" +
                                "          TargetPage: '" + page + "?result=1&sid=" + sid + "',\n" +
                                "          AppletService: '" + page + "?process=1&sid=" + sid + "',\n" +
                                "          BackgroundColor: '" + bgcolor + "',\n" +
                                "          Language: '" + Language + "',\n" +
                                "          MessageCallbackEx: 'messageCallbackEx',\n" +
                                "          HideDetailsButton: '" + HideDetailsButton.ToString().ToLower() + "'\n" +
                                "      };\n" +
                                "      var version = '1.6';\n" +
                                "      deployJava.runApplet(attributes, parameters, version);\n" +
                                "     function messageCallbackEx(status,messageId, message){\n" +
                                "                        document.getElementById('appletMessageEx').innerHTML='<b>'+message+'</b>';\n" +
                                "              }\n" +
                                "</script>\n" +
                                "<div style='font-family:"+FontFamily+";text-align:center;width:" + Width.Value + "px;height:" + Height.Value + "px;'>\n" +
                                "     <span style='" + TitleStyle+"' class='" + TitleCssClass + "'>eID Login</span><br />\n" +
                                "     <span style='" + MessageStyle + "' class='" + MessageCssClass + "' id='appletMessageEx'>Loading ...</span>\n" +
                                "     <center>"+
                                        "<div style=\"margin-top:10px;width:200px;height:" + CursorHeight.Value + "px;background-color:" + cbcolor + ";border:1px solid " + cbdcolor + ";\">"+
                                           "<marquee direction=\"right\" scrollamount=\"20\">"+
                                              "<div style=\"width:" + CursorWidth.Value + "px;height:" + (CursorHeight.Value-2) + "px;display:inline-block;background-color:" + ccolor + ";font-size:3px;" + cbgradient + ";border-left:1px solid "+ccolor+";border-top:1px solid "+ccolor+";border-right: 1px solid "+ccolor2+";border-bottom: 1px solid "+ccolor2+";\">&nbsp;</div>"+
                                           "</marquee>"+
                                        "</div>"+
                                     "</center>\n" +
                                "</div>";
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
         if (AuthMethod == Method.Applet)
            {
                string strProcess = "";
                string strResult = "";
                try
                {
                    strProcess = HttpContext.Current.Request.QueryString["process"];
                    strResult = HttpContext.Current.Request.QueryString["result"];
                }
                catch { }
                if ((strProcess!= "1")&&(strResult != "1")&&Visible)
                        output.Write(JsCode);
            }
            else
            {
                if ((Visible) && (HttpContext.Current.Request.QueryString["result"] != "1"))
                {
                    output.Write("<iframe src=\"" + GetLien() + "\" style=\"width:" + Width.Value + "px;height:" + Height.Value + "px;\" frameborder=\"0\" scrolling=\"no\"></iframe>");
                }

            }   
        }


        public EventHandler Identified { get; set; }

        private void MyMethod()
        {
            if ( (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["sid"])) 
                &&
                 (HttpContext.Current.Request.QueryString["process"]=="1")
                 )
            {
                HttpContext.Current.Response.Clear();
                try
                {
                    AuthnAppletService srv = new AuthnAppletService();
                    srv.ProcessRequest(HttpContext.Current);
                }
                catch 
                {
                }
                HttpContext.Current.Response.End();
                return;
            }
        }
        public string GetLien()
        {
            string wctx = System.Web.HttpContext.Current.Server.UrlEncode("rm=0&id=passive&ru=" + TargetPage);
            string target = System.Web.HttpContext.Current.Request.Url.ToString();
            if (target.IndexOf("?")>-1) target=target.Substring(0,target.IndexOf("?"));
            target = target.Replace(System.Web.HttpContext.Current.Request.Path, TargetPage);
            target = System.Web.HttpContext.Current.Server.UrlEncode(target);
            return "https://www.e-contract.be/eid-idp/protocol/ws-federation/auth-ident?wa=wsignin1.0&wtrealm=" + target + "&wctx=" + wctx + "&wct=2011-08-26T06%3a49%3a44Z";
        }
        public static void EContractMethod()
        {
            string saml = System.Web.HttpContext.Current.Request.Form["wresult"];
            //Identified =true;
            if (string.IsNullOrEmpty(saml)) return;

            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(saml);
                System.Xml.XmlNode rootNode = doc.DocumentElement;

                rootNode = FindChild(rootNode, "wst:requestsecuritytokenresponse");
                rootNode = FindChild(rootNode, "wst:requestedsecuritytoken");
                rootNode = FindChild(rootNode, "saml2:assertion");
                rootNode = FindChild(rootNode, "saml2:attributestatement");

                BeIDApplet.Identity.Address= GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/streetaddress");
                BeIDApplet.Identity.NationalNumber= GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier");
                BeIDApplet.Identity.Nationality= GetAttributeValue(rootNode, "be:fedict:eid:idp:nationality");
                BeIDApplet.Identity.PlaceOfBirth=GetAttributeValue(rootNode, "be:fedict:eid:idp:pob");
                BeIDApplet.Identity.Locality= GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality");
                BeIDApplet.Identity.LastName=GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname");
                BeIDApplet.Identity.FirstName=GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
                BeIDApplet.Identity.DateOfBirth= GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth");
                BeIDApplet.Identity.PostalCode= GetAttributeValue(rootNode, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode");
                BeIDApplet.Identity.Age= GetAttributeValue(rootNode, "be:fedict:eid:idp:age");
                BeIDApplet.Identity.Hash = "";
                BeIDApplet.Identity.Identified = !string.IsNullOrEmpty(BeIDApplet.Identity.NationalNumber);
            }
            catch
            {
            
            }
        }
        private static string GetAttributeValue(System.Xml.XmlNode root, string name)
        {
            foreach (System.Xml.XmlNode child in root.ChildNodes)
                if (child.Attributes["Name"].Value.ToLower() == name.ToLower())
                    return child.FirstChild.InnerText;
            return "";
        }
        private static System.Xml.XmlNode FindChild(System.Xml.XmlNode node, string name)
        {
            foreach (System.Xml.XmlNode child in node.ChildNodes)
                if (child.Name.ToLower() == name.ToLower()) return child;
            return null;
        }
    }
}
